# -*- coding: <utf-8> -*-
__author__ = 'David'

import os
import sys
import time
from datetime import datetime
import win32com.client
import pythoncom

import tweeter

quit = False

class MMEvents():
    def __init__(self):
        self.poster = tweeter.Tweeter()
        self.prev_track = ''

    def OnPlay(self):
        print 'Play event received'
        if self.prev_track.encode('UTF-8') != self.GetTitle():
            print 'New song - ', self.GetTitle(), ' - playing'
            self.prev_track = self.Player.CurrentSong.Title

            # Gather Song information
            artist = self.GetArtist()
            song = self.GetTitle()
            album = self.GetAlbum()
            length = self.GetLength()

            now = datetime.now()
            current_time = now.strftime('%Y-%m-%d %H:%M').encode('UTF-8')

            # Tweet the current song.  All strings need to be unicode to handle non-english songs.
            tweet = song + ' by ' + artist + ' on ' + album + ' (' + length + ') @ ' + current_time
            print tweet
            print
            
            self.poster.Post(tweet)

    def OnShutdown(self):
        global quit
        print 'MediaMonkey is closing. Ending script.'
        quit = True

    # Song information GET methods
    def GetArtist(self):
        return self.Player.CurrentSong.ArtistName.encode('UTF-8')

    def GetTitle(self):
        return self.Player.CurrentSong.Title.encode('UTF-8')

    def GetAlbum(self):
        return self.Player.CurrentSong.AlbumName.encode('UTF-8')

    def GetLength(self):
        return self.Player.CurrentSong.SongLengthString.encode('UTF-8')

def main():
    try:
        SDB = win32com.client.DispatchWithEvents('SongsDB.SDBApplication', MMEvents)
        SDB.ShutdownAfterDisconnect = False
    except:
        print "Couldn't connect to MediaMonkey. Exiting..."
        exit()

    while not quit:
        pythoncom.PumpWaitingMessages()
        time.sleep(0.1)

if __name__ == '__main__':
    main()